<template>
  <!-- 查：
       1：布局
       2：定义api
       3:导入api
       4:进入页面请求api
       5:存储数据并渲染
       6：与分页建立关联
          a:请求参数值要去分页组件绑定
          b:total值存储并绑定到分页组件
          c:页码改变与页容量改变都要请求api
      增：
       1：创建新增弹框组件
       2：在父组件导入注册使用
       3：点击新增打开弹框
       4：布局
       5：数据处理完善
       6：完成表单验证
       7：定义新增api
       8:导入api
       9:点击确定在表单验证通过后调用api
       10:调用成功
          a:关闭弹框
          b:清空表单数据与验证
          c:提示
          d:刷新父级列表
      删
        1：点击删除弹出确定框
        2：定义删除api
        3:导入删除api
        4:确定框定点确定调用删除api
        5：删除成功
           a:提示
           b:刷新列表
              有分页考虑
                  当前页只有一条数据，且 页码>1  页码-- 刷新
                  页码=1  刷新
 -->

  <div class="employees">
    <el-card>
      <div class="top">
        <div class="left">
          <i class="el-icon-info" />
          <span>共{{ total }}条记录</span>
        </div>
        <div class="right">
          <el-button size="small" type="danger" @click="outExcel">简单表头导出</el-button>
          <el-button size="small" type="info">复杂表头导出</el-button>
          <el-button size="small" type="success" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button size="small" type="primary" @click="addEvent">新增员工</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="bottom">
      <el-table :data="list">
        <el-table-column label="序号">
          <template v-slot="{$index}">
            {{ (page.page-1)*page.size+$index+1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="70px" />
        <el-table-column prop="staffPhoto" label="头像" width="70px">
          <template v-slot="{row}">
            <img v-errorimg="avatar" class="avatar" :src="row.staffPhoto" alt="" @click="imgClick(row.staffPhoto)">
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="workNumber" label="工号" />
        <!-- <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formOfEmployment" /> -->
        <el-table-column prop="formOfEmployment" label="聘用形式">
          <template v-slot="{row}">
            <!-- v-指令名:属性名.修饰符=值 -->
            <!-- <div v-changedata:hireType="row.formOfEmployment" /> -->
            <div v-changedata="{val:row.formOfEmployment,arg:'hireType'}" />
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" />
        <el-table-column prop="timeOfEntry" label="入职时间" :formatter="timeOfEntry" />
        <!-- <el-table-column prop="timeOfEntry" label="入职时间" /> -->
        <!-- <el-table-column prop="enableState" label="帐户状态" :formatter="enableState" /> -->
        <el-table-column prop="enableState" label="帐户状态">
          <template v-slot="{row}">
            <!-- <div v-changedata:workingState="row.enableState" /> -->
            <div v-changedata="{val:row.enableState,arg:'workingState'}" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="{row}">
            <el-button type="text" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="roleClick(row)">角色</el-button>
            <!-- <el-button v-if="$store.state.user.userInfo.roles.points.includes('employees_del')" type="text" @click="delEvent(row.id)">删除</el-button> -->
            <el-button v-if="controlBtn('employees_del')" type="text" @click="delEvent(row.id)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="page">
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[1,5,10,30,50,100, 200, 300, 400]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="sizeChange"
          @current-change="getData"
        />

      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <Add ref="add" @getData="getData" />
    <!-- 二维码弹框 -->
    <el-dialog title="打码预览" :visible.sync="showCode">
      <div style="text-align:center">
        <canvas ref="code" />
      </div>
    </el-dialog>
    <!-- 分配角色弹框 -->
    <Role ref="role" />
  </div>
</template>
<script>
import { sysUser, sysUserDelete } from '@/api/employees'
import jsCookie from 'js-cookie'
import employeesData from '@/api/constant/employees'
import Add from './components/Add.vue'
import dayjs from 'dayjs'
// import { export_json_to_excel } from '@/vendor/Export2Excel'
import Qrcode from 'qrcode'
import Role from './components/Role.vue'
export default {
  components: {
    Add,
    Role
  },
  data() {
    return {
      showCode: false,
      list: [],
      page: {
        page: 1,
        size: +jsCookie.get('employees_size') || 10
      },
      avatar: require('@/assets/common/img.jpeg'),
      total: 100
    }
  },
  async  created() {
    await this.getData()
  },
  methods: {
    async getData() {
      const res = await sysUser(this.page)
      this.list = res.data.rows
      this.total = res.data.total
      console.log('员工列表', res)
    },
    // 页容量改变
    sizeChange() {
      jsCookie.set('employees_size', this.page.size)
      this.getData()
    },
    // 格式化聘用形式
    formOfEmployment(row, column, value, index) {
      // value当前项的值
      const findItem = employeesData.hireType.find(item => {
        return +item.id === +value
      })
      return findItem ? findItem.value : '-'
    },
    // 状态转换
    enableState(row, column, value, index) {
      // value当前项的值
      const findItem = employeesData.workingState.find(item => {
        return +item.id === +value
      })
      return findItem ? findItem.value : '-'
    },
    // 入职时间转换
    timeOfEntry(row, column, value, index) {
      return dayjs(value).format('YYYY-MM-DD')
    },
    // 新增点击
    addEvent() {
      // 打开弹框
      this.$refs.add.show = true
    },
    // 删除点击
    async delEvent(id) {
      await this.$confirm('您确定删除该项吗', '提示')
      await sysUserDelete(id)
      this.$message.success('删除成功')
      // this.page.page = 1
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      this.getData()
    },
    // 导出excel
    async outExcel() {
      // 1：获取
      const res = await sysUser({
        page: 1,
        size: 999999
      })
      // console.log(res.data.rows)
      // 2：转换
      const data = res.data.rows.map((item, index) => {
        return [index + 1, item.username,
          item.staffPhoto,
          item.mobile,
          item.workNumber,
          this.formOfEmployment(null, null, item.formOfEmployment),
          item.departmentName,
          this.timeOfEntry(null, null, item.timeOfEntry)]
      })
      // 这种写法主体针对较大的插件使用
      // 导出插件
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // 生成excel
      export_json_to_excel({
        header: ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间'],
        data: data,
        filename: '员工列表'
      })
      // import('@/vendor/Export2Excel').then(res => {
      //   res.export_json_to_excel({
      //     header: ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间'],
      //     data: data,
      //     filename: '员工列表'
      //   })
      // })
      // export_json_to_excel({
      //   header: ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间'],
      //   data: data,
      //   filename: '员工列表'
      // })
    },
    // 头像点击生成二维码
    imgClick(avatar) {
      // 有头像地址才生成二维码
      if (avatar) {
        // 打开弹框
        this.showCode = true
        this.$nextTick(() => {
          // 弹框打开完成后再生成二维码
          Qrcode.toCanvas(this.$refs.code, avatar, { width: 300 })
        })
      }
    },
    // 角色点击
    roleClick(row) {
      // 打开分配角色弹框
      this.$refs.role.show = true
      // 调用获取用户角色id方法
      this.$refs.role.getInfo(row.id)
      console.log(row)
    }
  }
}
</script>
<style lang="scss" scoped>
// scoped:看得到的html部分管得到，看不到部分管不到
.employees{
  padding: 20px;
  .top{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left{
      padding:8px;
      border:1px solid #91d5ff;
      background-color: #e6f7ff;
      i{
        color:#409eff;
        margin-right:10px;
      }
    }
  }
  .bottom{
    margin-top:15px;
  }
  .page{
    padding-top:20px;
    text-align: center;
  }
  .avatar{
    width:50px;
    height:50px;
    object-fit: cover;
  }

}
</style>
